package com.x.client.activity

import android.support.v7.widget.GridLayoutManager
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.BaseQuickAdapter
import com.gg.baselibrary.BaseActivity
import com.gg.utils.StatusUtils
import com.gg.widget.LoadUtils
import com.gg.widget.navigationbar.DefaultNavigationBar
import com.jakewharton.rxbinding2.view.RxView
import com.lsxiao.apollo.core.Apollo
import com.x.client.R
import com.x.client.adapter.BodyAdapter
import com.x.client.adapter.ColorAdapter
import com.x.client.bean.CarStateBus
import com.x.client.bean.CarType
import com.x.client.bean.ColorBean
import com.x.client.net.ApiFactory
import com.x.client.net.Composers
import com.x.client.utils.BusTag
import com.x.client.utils.RouterClass
import com.x.client.utils.RouterField
import kotlinx.android.synthetic.main.activity_filter.*
import java.util.concurrent.TimeUnit

/**
 * Creator : GG
 * Date    : 2018/6/8
 * Mail    : gg.jin.yu@gmai.com
 * Explain :
 */
@Route(path = RouterClass.filter)
class CarFilterActivity : BaseActivity() {


    @Autowired(name = RouterField.data)
    lateinit var bus: CarStateBus

    private val ageArray: Array<String> by lazy { resources.getStringArray(R.array.car_age_array) }

    private val mileageArray: Array<String> by lazy { resources.getStringArray(R.array.mileage_array) }

    private val colorAdapter: ColorAdapter by lazy {
        ColorAdapter(data = listOf(
                ColorBean(colorName = "黑色", colorRes = R.drawable.ic_black),
                ColorBean(colorName = "白色", colorRes = R.drawable.ic_white),
                ColorBean(colorName = "银色", colorRes = R.drawable.ic_grey),
                ColorBean(colorName = "灰色", colorRes = R.drawable.ic_grayness),
                ColorBean(colorName = "红色", colorRes = R.drawable.ic_red),
                ColorBean(colorName = "蓝色", colorRes = R.drawable.ic_blue),
                ColorBean(colorName = "绿色", colorRes = R.drawable.ic_green),
                ColorBean(colorName = "香槟色", colorRes = R.drawable.ic_champagne),
                ColorBean(colorName = "紫色", colorRes = R.drawable.ic_purple),
                ColorBean(colorName = "橙色", colorRes = R.drawable.ic_orange),
                ColorBean(colorName = "棕色", colorRes = R.drawable.ic_brown),
                ColorBean(colorName = "其他", colorRes = R.drawable.ic_colorful)
        ))
    }

    private val bodyAdapter: BodyAdapter by lazy { BodyAdapter() }

    private val environAdapter: BodyAdapter by lazy {
        BodyAdapter(data = listOf(
                CarType(carTypeName = "国I"),
                CarType(carTypeName = "国II"),
                CarType(carTypeName = "国III"),
                CarType(carTypeName = "国IV"),
                CarType(carTypeName = "国VI"),
                CarType(carTypeName = "国V"),
                CarType(carTypeName = "欧I"),
                CarType(carTypeName = "欧II"),
                CarType(carTypeName = "欧III"),
                CarType(carTypeName = "欧IV"),
                CarType(carTypeName = "欧V")
        ))
    }

    private var bodyPosition = -1
    private var environPosition = -1


    override fun getLayoutRes(): Int = R.layout.activity_filter

    override fun initArguments() {
        super.initArguments()
        if (!this::bus.isInitialized)
            bus = CarStateBus()
    }

    override fun initTitle() {
        super.initTitle()
        StatusUtils.setStatusTextColor(true, this)
        StatusUtils.setStatusBar(this, false, false)
        DefaultNavigationBar.Builder(this)
                .setMiddleText(getString(R.string.filter))
                .setStatusBarHeight(StatusUtils.getStatusBarHeight(this))
                .setLeftIcon(R.drawable.ic_back_black)
                .setLeftClickListener(View.OnClickListener { finish() })
                .create()
    }

    override fun initView() {

        initCarAge()

        initMileage()

        initColor()

        initBody()

        initEnviron()

        RxView.clicks(reset)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.bindToLifecycle())
                .subscribe {
                    Apollo.emit(BusTag.filter, bus.apply {
                        colorBean = null
                        carOutColor = null

                        fromCarAge = null
                        toCarAge = null
                        fromCarAgeIndex = null
                        toCarAgeIndex = null

                        fromMileage = null
                        toMileage = null
                        fromMileageIndex = null
                        toMileageIndex = null

                        carTypeName = null
                        carTypeId = null

                        environ = null
                    })
                    finish()
                }

        RxView.clicks(confirm)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.bindToLifecycle())
                .subscribe {
                    Apollo.emit(BusTag.filter, bus)
                    finish()
                }
    }

    private fun initEnviron() {
        environRecyclerView.layoutManager = GridLayoutManager(this, 4)

        environRecyclerView.adapter = environAdapter

        environRecyclerView.isNestedScrollingEnabled = false

        environAdapter.onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->

            if (environPosition != position) {
                environAdapter.data.forEach {
                    it.status = false
                }
                environPosition = position
                environConf.text = environAdapter.data[environPosition].carTypeName
                environAdapter.data[environPosition].status = true
                environAdapter.notifyDataSetChanged()
            } else {
                environAdapter.data[environPosition].status = false
                environConf.text = ""
                bus.environ = null
                environAdapter.notifyItemChanged(environPosition)

            }
        }
        if (!bus.environ.isNullOrBlank())
            environConf.text = bus.environ
    }

    private fun initBody() {
        bodyRecyclerView.layoutManager = GridLayoutManager(this, 4)
        bodyRecyclerView.adapter = bodyAdapter

        bodyRecyclerView.isNestedScrollingEnabled = false

        bodyAdapter.onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->

            if (bodyPosition != position) {
                bodyAdapter.data.forEach {
                    it.status = false
                }
                bodyPosition = position
                bodyType.text = bodyAdapter.data[bodyPosition].carTypeName
                bus.carTypeId = bodyAdapter.data[bodyPosition].carTypeId
                bus.carTypeName = bodyAdapter.data[bodyPosition].carTypeName
                bodyAdapter.data[bodyPosition].status = true
                bodyAdapter.notifyDataSetChanged()
            } else {
                bodyAdapter.data[bodyPosition].status = false
                bodyType.text = ""
                bus.carTypeId = null
                bus.carTypeName = null
                bodyAdapter.notifyItemChanged(bodyPosition)
            }
        }
        if (!bus.carTypeName.isNullOrBlank())
            bodyType.text = bus.carTypeName
    }

    private fun initColor() {
        colorRecyclerView.layoutManager = GridLayoutManager(this, 5)

        colorRecyclerView.adapter = colorAdapter

        colorRecyclerView.isNestedScrollingEnabled = false

        colorAdapter.onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
            if (bus.carOutColor != colorAdapter.data[position].colorName) {
                color.text = colorAdapter.data[position].colorName
                colorAdapter.data.forEach {
                    it.status = false
                }
                colorAdapter.data[position].status = true
                bus.carOutColor = colorAdapter.data[position].colorName
                bus.colorBean = colorAdapter.data[position]
                colorAdapter.notifyDataSetChanged()
            } else {
                color.text = ""
                bus.carOutColor = null
                bus.colorBean = null
                colorAdapter.data[position].status = false
                colorAdapter.notifyDataSetChanged()
            }
        }
        if (!bus.carOutColor.isNullOrBlank())
            color.text = bus.carOutColor
    }

    private fun initMileage() {
        mileageRangeBar.setOnRangeSelectedListener { left, right ->
            setMileage(left, right)
        }
        setMileage(bus.fromMileageIndex ?: 0, bus.toMileageIndex ?: 5)
    }

    private fun initCarAge() {
        ageRangeBar.setOnRangeSelectedListener { left, right ->
            setCarAge(left, right)
        }
        setCarAge(bus.fromCarAgeIndex ?: 0, bus.toCarAgeIndex ?: 7)
    }

    private fun setCarAge(left: Int, right: Int) {
        if (right == ageArray.size - 1 && left == 0) {
            carAge.text = ageArray[right]
            bus.fromCarAge = null
            bus.toCarAge = null
        } else if (right == ageArray.size - 1 && left != 0) {
            carAge.text = ageArray[left] + "年以上"
            bus.fromCarAge = ageArray[left].toInt()
            bus.toCarAge = null
        } else if (right != ageArray.size - 1 && left != 0) {
            carAge.text = ageArray[left] + "-" + ageArray[right] + "年"
            bus.fromCarAge = ageArray[left].toInt()
            bus.toCarAge = ageArray[right].toInt()
        } else if (right != ageArray.size - 1 && left == 0) {
            carAge.text = ageArray[right] + "年以内"
            bus.fromCarAge = null
            bus.toCarAge = ageArray[right].toInt()
        }
        bus.fromCarAgeIndex = left
        bus.toCarAgeIndex = right
    }

    private fun setMileage(left: Int, right: Int) {
        if (right == mileageArray.size - 1 && left == 0) {
            mileage.text = mileageArray[right]
            bus.fromMileage = null
            bus.toMileage = null
        } else if (right == mileageArray.size - 1 && left != 0) {
            mileage.text = mileageArray[left] + "万公里以上"
            bus.fromMileage = mileageArray[left].toInt()
            bus.toMileage = null
        } else if (right != mileageArray.size - 1 && left != 0) {
            mileage.text = mileageArray[left] + "-" + mileageArray[right] + "万公里"
            bus.fromMileage = mileageArray[left].toInt()
            bus.toMileage = mileageArray[right].toInt()
        } else if (right != mileageArray.size - 1 && left == 0) {
            mileage.text = mileageArray[right] + "万公里以内"
            bus.fromMileage = null
            bus.toMileage = mileageArray[right].toInt()
        }
        bus.fromMileageIndex = left
        bus.toMileageIndex = right
    }

    override fun initData() {
        LoadUtils.show(this)
        ApiFactory.getErpApi()
                .bodyType()
                .compose(Composers.handleError())
                .compose(this.bindToLifecycle())
                .subscribe({
                    LoadUtils.hidden()
                    it.forEach {
                        if (it.carTypeId == bus.carTypeId) {
                            it.status = true
                            bodyType.text = it.carTypeName
                            return@forEach
                        }
                    }
                    bodyAdapter.setNewData(it)
                }, {
                    LoadUtils.hidden()
                })
    }
}